var express = require('express');
var router = express.Router();
var fs = require('fs');
var PATH = './public/data/';
/* GET home page. */
router.get('/', function(req, res, next) {
  if(!req.session.user){
    res.redirect('login?valid=1');


  }
  res.redirect('index', { title: 'Express' });
});
router.get('/index',function(req,res,next){
  if(!req.session.user){
     res.redirect('/login?valid=1');

  }
  var user = req.session.user;
  console.info(user);
  res.render('index', { title:'用户管理',username:user.username});
});
router.get('/login', function(req, res, next) {
  res.render('login', {});
});
router.get('/add',function(req,res,next){
  if(!req.session.user){
     res.redirect('/login?valid=1');
  }
  res.render('add',{});
});
router.get('/editUI',function(req,res,next){
  if(!req.session.user){
    res.redirect('/login?valid=1');
  }
//文件名
  var type = req.param('type') || '';
  //关键字段
  var _id = req.param('id');

  if(!type || !_id ){
    return res.send({
      status:0,
      info:'提交的字段不全'
    });
  }
  var filePath = PATH + type + '.json';
  fs.readFile(filePath, function(err, data){
    if(err){
      return res.send({
        status:0,
        info: '读取数据失败'
      });
    }
    var arr = JSON.parse(data.toString());
    //代表每一条记录
    var _index=-1;
    for(var i=0;i<arr.length;i++)
    {
      if(arr[i].id==_id)
      {
        _index=i;break;
      }
    }
    if(_index>=0)
    {
      var _obj=arr[_index];
      res.render('edit',_obj);
    }else
    {
      return res.send({
        status:0,
        info: '读取数据失败'
      });
    }



  });

});
router.get('/logout',function(req,res,next)
{
  req.session.user = null;
  res.redirect('login');
});
module.exports = router;
